package cn.tedu.v3;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;


public class Client {
    private Socket socket;
    private String ip;
    public Client(){
        try {
            socket=new Socket("127.0.0.1",3333);
            ip=socket.getInetAddress().getHostAddress();
        } catch (UnknownHostException e) {
            System.out.println("IP地址有问题，请询问服务器端");
            e.printStackTrace();
        }catch (IOException e) {
            System.out.println("客户端主动退出了");
        }
    }
    public void start() {
       PrintWriter pw=null;
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF8"));

            pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8")), true);

            new Thread(() -> {
                try {
                    String message;
                    while ((message = br.readLine()) != null) {
                        System.out.println(ip + "服务器端说：" + message/*br.readLine()*/);
                    }
                } catch (IOException e) {
                    System.out.println("服务器端断开了");
                }finally {
                    if (br != null)
                        try {
                            br.close();
                        } catch (IOException e) {
                            System.out.println("客户端离开");
                        }
                }
            }).start();

            System.out.println(ip + "客户端：请输入文字：");
            Scanner input = new Scanner(System.in);
            while (true) {
                String say = input.nextLine();
                pw.println("客户端说" + say);
                System.out.println("发送");
                System.out.println("客户端请输入文字.....");
            }
        } catch (UnsupportedEncodingException e) {
            System.out.println("客户端与服务器端，字符集不一致");
        } catch (IOException e) {
            System.out.println("客户端断开链接");
        } finally {

                    if (pw != null)
                        pw.close();
                    try {
                        socket.close();
                    } catch (IOException e) {
                        System.out.println("客户端离开");
                    }
                    if (socket != null && !socket.isClosed()) {
                        System.out.println(ip + "客户端关闭成功");
                        try {
                            socket.close();
                        } catch (IOException e) {
                            System.out.println(ip + "客户端关闭失败");
                        }
                    }
                }
        }


    public static void main(String[] args) {
        Client client=new Client();
        client.start();

    }
}